<template>
  <basic-container>
    <el-form ref="queryForm"
             :model="queryParams"
             :inline="true"
             label-width="80px">
      <el-form-item label="任务名称"
                    prop="searchParams.search_eq_jobName">
        <el-input v-model="queryParams.searchParams.search_eq_jobName"
                  placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="任务组"
                    prop="searchParams.search_eq_jobGroup">
        <el-select v-model="queryParams.searchParams.search_eq_jobGroup" placeholder="请选择"  @change="selectChange">
          <el-option
                  v-for="dict in jobGroupOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态"
                    prop="searchParams.search_eq_status">
        <el-select v-model="queryParams.searchParams.search_eq_status" placeholder="请选择">
          <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10"
            class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
                type="success"
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
        >编辑
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
                type="warning"
                icon="el-icon-time"
                size="mini" @click="openLog"
        >任务日志
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
                type="warning"
                icon="el-icon-download"
                size="mini"
        >导出
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading"
              :data="userList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="jobId"/>
      <el-table-column label="任务名称" align="center" prop="jobName"/>
      <el-table-column label="任务组名" align="center" prop="jobGroup" :formatter="groupFormat"/>
      <el-table-column label="调用目标字符串" align="center" prop="invokeTarget"/>
      <el-table-column label="cron执行表达式" align="center" prop="cronExpression"/>
      <el-table-column label="使用状态"
                       align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     active-value="0"
                     inactive-value="1"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="remark" :formatter="dFormat">
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-row :gutter="10"
                  class="mb8">
            <el-col :span="1.5">
              <el-button size="small"
                         type="text"
                         icon="el-icon-edit"
                         @click="runOne(scope.row)"
              >执行一次
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button size="small"
                         type="text"
                         icon="el-icon-delete"
                         class="deleteBtn"
                         @click="jobInfo(scope.row)"
              >详细
              </el-button>
            </el-col>
          </el-row>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"/>


    <!-- 添加或编辑收费员信息对话框 -->
    <el-dialog :title="title[statusDialog]"
               :visible.sync="open"
               width="40%"
               append-to-body
               :close-on-click-modal="false">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="80px">
        <el-row v-if="statusDialog!='info'">
          <el-col :span="12">
            <el-form-item label="任务名称"
                          prop="jobName">
              <el-input v-model="form.jobName"
                        placeholder="请输入任务名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务组"
                          prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择" >
                <el-option
                        v-for="dict in jobGroupOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="statusDialog=='info'">
          <el-col :span="12">
            <el-form-item label="任务ID"
                          prop="jobId">
              <el-input v-model="form.jobId"
                        placeholder="请输入任务名称" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称"
                          prop="jobName">
              <el-input v-model="form.jobName"
                        placeholder="请输入任务名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="statusDialog=='info'">
          <el-col :span="12">
            <el-form-item label="任务组"
                          prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择" :disabled="statusDialog=='info'">
                <el-option
                        v-for="dict in jobGroupOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次时间"
                          prop="nextExecution">
              <el-input v-model="form.nextExecution"
                        placeholder="请输入任务名称" :disabled="statusDialog=='info'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="调用目标"
                      prop="invokeTarget">
          <el-input v-model="form.invokeTarget"
                    placeholder="请输入调用目标" :disabled="statusDialog=='info'"/>
        </el-form-item>
        <el-form-item label="cron执行表达式"
                      prop="cronExpression">
          <el-input v-model="form.cronExpression"
                    placeholder="请输入cron执行表达式" :disabled="statusDialog=='info'"/>
        </el-form-item>
        <el-form-item label="是否并发"
                      prop="concurrent">
          <el-radio-group v-model="form.concurrent" :disabled="statusDialog=='info'">
            <el-radio v-for="dict in concurrentOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="错误策略"
                      prop="misfirePolicy" >
          <el-radio-group v-model="form.misfirePolicy" :disabled="statusDialog=='info'">
            <el-radio v-for="dict in misfirePolicyOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用状态" prop="status" >
          <el-radio-group v-model="form.status" :disabled="statusDialog=='info'">
            <el-radio v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm" v-if="statusDialog!='info'">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </basic-container>
</template>

<script>
  import {addJob, delJob, listJob, updateJob,startJob,runOneJob} from "@/api/monitor/job";
  import {dateFormat} from '@/util/date'

  export default {
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 用户信息表格数据
        userList: [],
        // 弹出层标题
        title: {
          add: '新增任务',
          edit: '编辑任务',
          info: '任务详细',
        },
        statusDialog: "",
        // 是否显示弹出层
        open: false,
        jobGroupOptions: [],
        concurrentOptions: [],
        misfirePolicyOptions: [],
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          searchParams:{
            search_eq_jobName: undefined,
            search_eq_jobGroup: undefined,
            search_eq_status: undefined,
          }

        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          jobName: [
            {required: true, message: "任务名称不能为空", trigger: "blur"}
          ],
          jobGroup: [
            {required: true, message: "任务组不能为空", trigger: "blur"}
          ],
          invokeTarget: [
            {required: true, message: "调用目标不能为空", trigger: "blur"}
          ],
          cronExpression: [
            {required: true, message: "corn表达式不能为空", trigger: "blur"}
          ],
          status: [
            {required: true, message: "状态不能为空", trigger: "blur"}
          ],
        }
      }

    },
    created() {
      this.getList();
      this.getDicts("job_group").then(response=>{
        this.jobGroupOptions =response.data.data;
      });
      this.getDicts("job_disallow").then(response=>{
        this.concurrentOptions =response.data.data;
      });
      this.getDicts("job_misfire_policy").then(response=>{
        this.misfirePolicyOptions =response.data.data;
      });
      this.getDicts("job_status").then(response=>{
        this.statusOptions =response.data.data;
      });
    },
    methods: {
      /** 搜索按钮操作 */
      handleQuery() {
        for (let key in this.queryParams.searchParams) {
          if(this.queryParams.searchParams[key]!=undefined){
            if (this.queryParams.searchParams[key] == "") {
              this.queryParams.searchParams[key] = undefined;
              continue;
            }
            if(this.queryParams.searchParams[key].length>0){
              if(!this.queryParams.searchParams[key].constructor == Array){
                if(!(this.queryParams.searchParams[key].replace(" ", "").trim().length > 0)){
                  this.queryParams.searchParams[key] = undefined;
                  continue;
                }
              }
            }
          }
        }
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          jobId: undefined,
          jobName: undefined,
          jobGroup: undefined,
          nextExecution: undefined,
          invokeTarget: undefined,
          cronExpression: undefined,
          concurrent: "1",
          misfirePolicy: "0",
          status: "1",
          createTime: undefined,
          createBy: undefined,
          updateTime: undefined,
          updateBy: undefined
        };
        this.resetForm("form");
      },
      /** 查询收费员信息列表 */
      getList() {
        this.loading = true;
        listJob(this.queryParams).then(response => {
          const data = response.data;
          if (response.status===200&&data.code === "00") {
            this.userList = data.data.rows;
            this.total = data.data.total;
          } else {
            this.msgError(data.msg);
          }

          this.loading = false;
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        // this.ids = selection.map(item => item.id)
        this.ids = selection;
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.statusDialog = 'add';
      },
      /** 编辑按钮操作 */
      handleUpdate(row) {
        if (row.id) {
          this.form = JSON.parse(JSON.stringify(row));
        } else {
          this.form = JSON.parse(JSON.stringify(this.ids[0]));
        }
        this.form.status = this.form.status + "";
        this.open = true;
        this.statusDialog = 'edit';
      },
      jobInfo(row){
        this.form = JSON.parse(JSON.stringify(row));
        this.form.status = this.form.status + "";
        this.form.nextExecution = dateFormat(new Date(this.form.nextExecution));
        this.open = true;
        this.statusDialog = 'info';
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateJob(this.form).then(response => {
                const data = response.data;
                if (response.status === 200 && data.code === "00") {
                  this.msgSuccess("编辑成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addJob(this.form).then(response => {
                const data = response.data;
                if (response.status === 200 && data.code === "00") {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.id || this.ids;
        let tt = '';
        if (row.id == undefined) {
          tt = '是否确认删除【' + this.ids.length + '】条数据吗?';
        } else {
          tt = '是否确认删除为"' + row.dictName + '"的数据项?';
        }
        this.$confirm(tt, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delJob(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      // 用户状态编辑
      handleStatusChange(row) {
        startJob(row).then(response => {
          let msg = response.data.msg;
          this.msgSuccess(msg);
        });
      },
      runOne(row) {
        runOneJob(row.jobId).then(response => {
          let msg = response.data.msg;
          this.msgSuccess(msg);
        });
      },
      selectChange(value) {
        this.queryParams.searchParams.search_eq_jobGroup = value;
        this.getList();
      },
      openLog() {
        this.$router.push({
          path: this.$router.$avueRouter.getPath({
            name: "任务日志",
            src: "/taskLog/index"
          }, {}),
          query: {}
        });
      },
      groupFormat(row) {
        return this.selectDictLabel(this.jobGroupOptions,row.jobGroup);
      },
      dFormat(row) {
        if (row.createTime == null) {
          return "/";
        }
        return dateFormat(new Date(row.createTime));
      }
    }
  };
</script>

<style>

</style>
